"""
边缘优化预览面板模块
"""

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import numpy as np
import cv2
from typing import Callable

from ...utils import get_logger


class EdgePreviewPanel:
    """边缘优化预览面板类"""
    
    def __init__(self, parent: tk.Widget, on_param_change: Callable = None):
        """
        初始化预览面板
        
        Args:
            parent: 父容器
            on_param_change: 参数变化回调函数
        """
        self.parent = parent
        self.on_param_change = on_param_change
        self.logger = get_logger(__name__)
        
        # 创建面板
        self._create_panel()
    
    def _create_panel(self):
        """创建预览面板"""
        # 预览标题
        self.preview_title = ttk.Label(
            self.parent,
            text="请先选择一个缩略图查看完整预览",
            font=("Arial", 12, "bold")
        )
        self.preview_title.pack(pady=5)
        
        # 预览描述
        self.preview_description = ttk.Label(
            self.parent,
            text="",
            font=("Arial", 10),
            foreground="gray"
        )
        self.preview_description.pack(pady=2)
        
        # 预览画布
        self.preview_canvas = tk.Canvas(
            self.parent,
            bg="#2b2b2b",
            highlightthickness=1,
            highlightbackground="gray"
        )
        self.preview_canvas.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 参数调节区域
        self._create_params_panel()
    
    def _create_params_panel(self):
        """创建参数调节面板"""
        self.params_frame = ttk.Frame(self.parent, padding=10)
        self.params_frame.pack(fill=tk.X, pady=5)
        self.params_frame.pack_forget()  # 默认隐藏
        
        # 平滑度滑块
        smooth_row = ttk.Frame(self.params_frame)
        smooth_row.pack(fill=tk.X, pady=5)
        
        ttk.Label(smooth_row, text="平滑强度:", font=("Arial", 10, "bold"), width=10).pack(side=tk.LEFT)
        self.smooth_var = tk.DoubleVar(value=0.5)
        self.smooth_scale = ttk.Scale(
            smooth_row,
            from_=0.0,
            to=1.0,
            orient=tk.HORIZONTAL,
            variable=self.smooth_var,
            command=self._on_smooth_change
        )
        self.smooth_scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        self.smooth_value_label = ttk.Label(smooth_row, text="0.50", width=6, font=("Arial", 10))
        self.smooth_value_label.pack(side=tk.LEFT, padx=5)
        ttk.Label(smooth_row, text="(0=锐利 → 1=柔和)", foreground="gray").pack(side=tk.LEFT)
        
        # 硬化度滑块
        harden_row = ttk.Frame(self.params_frame)
        harden_row.pack(fill=tk.X, pady=5)
        
        ttk.Label(harden_row, text="硬化强度:", font=("Arial", 10, "bold"), width=10).pack(side=tk.LEFT)
        self.harden_var = tk.DoubleVar(value=0.5)
        self.harden_scale = ttk.Scale(
            harden_row,
            from_=0.0,
            to=1.0,
            orient=tk.HORIZONTAL,
            variable=self.harden_var,
            command=self._on_harden_change
        )
        self.harden_scale.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        self.harden_value_label = ttk.Label(harden_row, text="0.50", width=6, font=("Arial", 10))
        self.harden_value_label.pack(side=tk.LEFT, padx=5)
        ttk.Label(harden_row, text="(0=扩展 → 1=收缩)", foreground="gray").pack(side=tk.LEFT)
        
        # 重置按钮
        reset_row = ttk.Frame(self.params_frame)
        reset_row.pack(fill=tk.X, pady=5)
        ttk.Button(
            reset_row,
            text="重置为默认值",
            command=self.reset_params,
            width=15
        ).pack(side=tk.LEFT, padx=5)
        
        ttk.Label(
            reset_row,
            text="💡 调节滑块可实时预览效果",
            foreground="#0066cc",
            font=("Arial", 9, "italic")
        ).pack(side=tk.LEFT, padx=20)
    
    def _on_smooth_change(self, value):
        """平滑度变化"""
        self.smooth_value_label.config(text=f"{self.smooth_var.get():.2f}")
        if self.on_param_change:
            self.on_param_change()
    
    def _on_harden_change(self, value):
        """硬化度变化"""
        self.harden_value_label.config(text=f"{self.harden_var.get():.2f}")
        if self.on_param_change:
            self.on_param_change()
    
    def show_params_panel(self):
        """显示参数面板"""
        self.params_frame.pack(fill=tk.X, pady=5)
    
    def hide_params_panel(self):
        """隐藏参数面板"""
        self.params_frame.pack_forget()
    
    def reset_params(self):
        """重置参数"""
        self.smooth_var.set(0.5)
        self.harden_var.set(0.5)
        self.smooth_value_label.config(text="0.50")
        self.harden_value_label.config(text="0.50")
        if self.on_param_change:
            self.on_param_change()
    
    def get_params(self) -> dict:
        """获取当前参数"""
        return {
            'smooth_amount': self.smooth_var.get(),
            'harden_amount': self.harden_var.get()
        }
    
    def update_title(self, title: str, description: str = ""):
        """更新标题和描述"""
        self.preview_title.config(text=title)
        self.preview_description.config(text=description)
    
    def display_image(self, image: np.ndarray):
        """显示预览图像"""
        # 清空画布
        self.preview_canvas.delete("all")
        
        # 获取画布尺寸
        self.preview_canvas.update()
        canvas_width = self.preview_canvas.winfo_width()
        canvas_height = self.preview_canvas.winfo_height()
        
        if canvas_width <= 1 or canvas_height <= 1:
            canvas_width = 700
            canvas_height = 400
        
        # 调整图片大小
        h, w = image.shape[:2]
        scale = min(canvas_width / w, canvas_height / h) * 0.95
        new_w = int(w * scale)
        new_h = int(h * scale)
        
        resized = cv2.resize(image, (new_w, new_h))
        
        # 转换为PIL
        pil_image = Image.fromarray(resized)
        photo = ImageTk.PhotoImage(pil_image)
        
        # 居中显示
        x = (canvas_width - new_w) // 2
        y = (canvas_height - new_h) // 2
        
        self.preview_canvas.create_image(x, y, anchor=tk.NW, image=photo)
        self.preview_canvas.image = photo

